package com.hugh.commom.netty.server.codec;

import com.alibaba.fastjson.JSON;
import com.hugh.commom.RpcRequest;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Objects;

@Slf4j
public class ServerProtocolDecoder extends MessageToMessageDecoder<ByteBuf> {

    private static final int LENGTH_SIZE = 2;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> out) throws Exception {
        log.info("server 接受数据 长度为:{}", byteBuf.readableBytes());
        if(byteBuf.readableBytes() > LENGTH_SIZE) {
            byteBuf.readInt();
            //直接用byteBuf会报 io.netty.handler.codec.DecoderException: java.lang.UnsupportedOperationException: direct buffer错误
            ByteBuf tmpBuf = byteBuf.readBytes(byteBuf.readableBytes());
            byte[] bs = new byte[tmpBuf.readableBytes()];
            tmpBuf.readBytes(bs);
            RpcRequest requestMessage = new RpcRequest();
            requestMessage = requestMessage.deserialize(RpcRequest.class, bs);
            log.info("server 接受数据，反序列化完成:{}, byteBuf的长度是:{}", JSON.toJSON(requestMessage), byteBuf.readableBytes());
            if (Objects.nonNull(requestMessage)) {
                out.add(requestMessage);
            }
        }
    }
}
